import React, { memo, useEffect, useCallback, useState } from 'react';
import { Modal, Form, Input, Button, Space, message, ColorPicker, InputNumber } from 'antd';
import { FolderOutlined, NumberOutlined } from '@ant-design/icons';
import type { ICourseCategoryFormProps } from '@/types/components/courseCategory';
import type { ICourseCategoryCreateRequest, ICourseCategoryUpdateRequest } from '@/types/course';
import { CourseCategoryStatusEnum } from '@/types/course';
import styles from './CourseCategoryForm.module.css';

const { TextArea } = Input;

/**
 * 课程分类表单组件
 * @description 用于创建和编辑课程分类信息的表单组件
 */
const CourseCategoryForm: React.FC<ICourseCategoryFormProps> = memo(({
  category,
  visible,
  mode,
  onSubmit,
  onCancel,
  loading = false,
  existingCategories = []
}) => {
  const [form] = Form.useForm();
  const [selectedColor, setSelectedColor] = useState('#52c41a');

  // 表单初始化
  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && category) {
        // 编辑模式，填充现有数据
        form.setFieldsValue({
          name: category.name,
          categoryCode: category.categoryCode,
          description: category.description,
          color: category.color,
          sortOrder: category.sortOrder,
          status: category.status
        });
        setSelectedColor(category.color);
      } else {
        // 创建模式，重置表单
        form.resetFields();
        const defaultColor = '#52c41a';
        const defaultSortOrder = Math.max(...existingCategories.map(c => c.sortOrder), 0) + 10;
        form.setFieldsValue({
          color: defaultColor,
          sortOrder: defaultSortOrder,
          status: CourseCategoryStatusEnum.ACTIVE // 默认状态为正常
        });
        setSelectedColor(defaultColor);
      }
    }
  }, [visible, mode, category, form, existingCategories]);

  // 处理表单提交
  const handleSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      
      // 构造提交数据
      const submitData = mode === 'edit' && category ? {
        id: category.id,
        name: values.name.trim(),
        categoryCode: values.categoryCode.trim(),
        description: values.description?.trim() || undefined,
        color: values.color,
        sortOrder: values.sortOrder,
        status: values.status
      } as ICourseCategoryUpdateRequest : {
        name: values.name.trim(),
        categoryCode: values.categoryCode.trim(),
        description: values.description?.trim() || undefined,
        color: values.color,
        sortOrder: values.sortOrder,
        status: values.status
      } as ICourseCategoryCreateRequest;

      await onSubmit(submitData);
      form.resetFields();
    } catch (error) {
      console.error('表单提交失败:', error);
      if (error instanceof Error) {
        message.error(error.message);
      }
    }
  }, [form, onSubmit]);

  // 处理取消操作
  const handleCancel = useCallback(() => {
    form.resetFields();
    onCancel();
  }, [form, onCancel]);

  // 分类名称验证规则
  const validateCategoryName = useCallback(async (_: any, value: string) => {
    if (!value) {
      throw new Error('请输入分类名称');
    }
    if (value.length < 2) {
      throw new Error('分类名称长度不能少于2个字符');
    }
    
    // 检查重复（编辑时排除自身）
    const isDuplicate = existingCategories.some(cat => 
      cat.name === value.trim() && 
      (mode === 'create' || cat.id !== category?.id)
    );
    
    if (isDuplicate) {
      throw new Error('分类名称已存在');
    }
  }, [existingCategories, mode, category]);

  // 分类代码验证规则
  const validateCategoryCode = useCallback(async (_: any, value: string) => {
    if (!value) {
      throw new Error('请输入分类代码');
    }
    if (value.length < 2) {
      throw new Error('分类代码长度不能少于2位');
    }
    if (!/^[A-Za-z0-9-_]+$/.test(value)) {
      throw new Error('分类代码只能包含字母、数字、横线和下划线');
    }
    
    // 检查重复（编辑时排除自身）
    const isDuplicate = existingCategories.some(cat => 
      cat.categoryCode === value.trim() && 
      (mode === 'create' || cat.id !== category?.id)
    );
    
    if (isDuplicate) {
      throw new Error('分类代码已存在');
    }
  }, [existingCategories, mode, category]);

  // 处理颜色变化
  const handleColorChange = useCallback((color: any) => {
    const colorValue = typeof color === 'string' ? color : color.toHexString();
    setSelectedColor(colorValue);
    form.setFieldValue('color', colorValue);
  }, [form]);

  return (
    <Modal
      title={
        <div className={styles.modalTitle}>
          <FolderOutlined className={styles.titleIcon} />
          {mode === 'create' ? '添加分类' : '编辑分类'}
        </div>
      }
      open={visible}
      onCancel={handleCancel}
      footer={
        <Space>
          <Button onClick={handleCancel}>
            取消
          </Button>
          <Button
            type="primary"
            loading={loading}
            onClick={handleSubmit}
          >
            {mode === 'create' ? '添加' : '保存'}
          </Button>
        </Space>
      }
      width={520}
      destroyOnHidden
      className={styles.categoryFormModal}
    >
      <Form
        form={form}
        layout="vertical"
        className={styles.categoryForm}
        autoComplete="off"
      >
        <div className={styles.formRow}>
          <Form.Item
            name="name"
            label="分类名称"
            rules={[
              { validator: validateCategoryName }
            ]}
            className={styles.halfWidth}
          >
            <Input
              prefix={<FolderOutlined />}
              placeholder="请输入分类名称"
              maxLength={50}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="categoryCode"
            label="分类代码"
            rules={[
              { validator: validateCategoryCode }
            ]}
            className={styles.halfWidth}
          >
            <Input
              placeholder="请输入分类代码"
              maxLength={20}
              showCount
            />
          </Form.Item>
        </div>

        <div className={styles.formRow}>
          <Form.Item
            name="color"
            label="分类颜色"
            rules={[{ required: true, message: '请选择分类颜色' }]}
            className={styles.halfWidth}
          >
            <div className={styles.colorPickerWrapper}>
              <ColorPicker
                value={selectedColor}
                onChange={handleColorChange}
                showText
                format="hex"
                presets={[
                  {
                    label: '推荐颜色',
                    colors: [
                      '#52c41a', '#1890ff', '#faad14', '#f5222d',
                      '#722ed1', '#eb2f96', '#13c2c2', '#fa8c16',
                      '#a0d911', '#2f54eb', '#fadb14', '#ff4d4f'
                    ]
                  }
                ]}
              />
            </div>
          </Form.Item>

          <Form.Item
            name="sortOrder"
            label="排序权重"
            rules={[
              { required: true, message: '请输入排序权重' },
              { type: 'number', min: 0, max: 9999, message: '排序权重必须在0-9999之间' }
            ]}
            className={styles.halfWidth}
          >
            <InputNumber
              prefix={<NumberOutlined />}
              placeholder="排序权重"
              min={0}
              max={9999}
              step={10}
              className={styles.fullWidth}
            />
          </Form.Item>
        </div>

        <Form.Item
          name="description"
          label="分类描述"
        >
          <TextArea
            placeholder="请输入分类描述"
            rows={3}
            maxLength={200}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  );
});

CourseCategoryForm.displayName = 'CourseCategoryForm';

export default CourseCategoryForm;